package org.luxor.commons.log.component;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ExtendOutputStream extends ServletOutputStream {

    private ByteArrayOutputStream outputStream;
    private HttpServletResponse response;
    private boolean enabledFlush;

    public ExtendOutputStream(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, boolean enabledFlush) {
        this.outputStream = byteArrayOutputStream;
        this.response = response;
        this.enabledFlush = enabledFlush;
    }

    @Override
    public void write(int b) {
        this.outputStream.write(b);
    }

    @Override
    public void write(byte[] b) throws IOException {
        this.outputStream.write(b);
    }

    @Override
    public boolean isReady() {
        return true;
    }

    @Override
    public void setWriteListener(WriteListener arg0) {
    }

    @Override
    public void flush() throws IOException {
        if (!this.response.isCommitted() && this.enabledFlush) {
            byte[] content = this.outputStream.toByteArray();
            ServletOutputStream outputStream = this.response.getOutputStream();
            outputStream.write(content);
            outputStream.flush();
        }
    }
}